package middlewares

import (
	"gonexample/gone/e"
	"gonexample/gone/gjwt"
	"gonexample/libs/helper"
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// JwtAuth auth
func JwtAuth() gin.HandlerFunc {
	return func(c *gin.Context) {

		uid := 0
		status := e.OK

		// token := c.GetHeader("Authorization")
		token := c.GetHeader("GoneToken")

		if token == "" {
			status = e.ErrEmptyGoneToken
		} else {
			claims, err := gjwt.ParseToken(token)
			if err != nil {
				switch err.(*jwt.ValidationError).Errors {
				case jwt.ValidationErrorExpired:
					status = e.ErrExpiredGoneToken
				default:
					status = e.ErrFailedGoneToken
				}
			} else {
				uid = claims.UserID
			}
		}

		if status != e.OK {
			c.JSON(http.StatusUnauthorized, e.New(status))
			c.Abort()
			return
		}

		c.Set("uid", uid)

		c.Next()
	}

}

// Auth session auth
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		uid := 0

		session := sessions.Default(c)

		uid = helper.InterfaceToInt(session.Get("uid"))

		if uid == 0 {
			c.JSON(200, e.New(4004))
			c.Abort()
			return
		}

		c.Set("uid", uid)

		c.Next()
	}
}
